package cxm.mmp.aud;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import cxm.lib.util.MyLog;

public class XAudioPlayer extends XAudioBase {
	private AudioTrack track = null;

	public XAudioPlayer() {
		// set channel type
		this.channel = AudioFormat.CHANNEL_OUT_MONO;
	}

	protected int onBeforeRun() {
		int maxJitter = AudioTrack.getMinBufferSize(freq,
				this.channel, this.audioFormat);
		this.track = new AudioTrack(AudioManager.STREAM_MUSIC, this.freq,
				this.channel, this.audioFormat, maxJitter, AudioTrack.MODE_STREAM);

		/*
		// init AEC
		if (AcousticEchoCanceler.isAvailable()) {
			this.echoCanceler = AcousticEchoCanceler.create(this.track.getAudioSessionId());
			this.echoCanceler.setEnabled(true);
		}
		else
			MyLog.Log(MyLog.Level.Warning, "Do not support AEC");
		*/
					
		this.track.play();
		return 0;
	}

	protected int onAfterRun() {
		// release resource
		this.track.stop();
		this.track.release();
		this.track = null;
		
		/*
		// release AEC
		if (null != this.echoCanceler) {
			this.echoCanceler.setEnabled(false);
			this.echoCanceler.release();
		}
		*/

		return 0;
	}

	protected int onRunOnce() {
		if (null == this.recording)
			// do nothing, treate as success if data source empty
			return 0;
		
		// read data from recording
		int readLength = this.recording.onRecordData(this.buffer, 0, this.buffer.length);
		if (readLength <= 0) {
			MyLog.Log(MyLog.Level.Error, "Read data failed: " + readLength);
			return readLength;
		}
		
		// write to track
		int writeLength = 0;
		while (writeLength < readLength) {
			// write to track
			int ret = track.write(this.buffer, writeLength, readLength - writeLength);
			if (ret <= 0) {
				MyLog.Log(MyLog.Level.Error, "Cannot write data: " + ret);
				return ret;
			}
			writeLength += ret;
		}

		return 0;
	}
}
